<template>
  <div class="wrap">
    <affix :label="$t('monitor.cmonitor')" >
      <el-row :gutter="20">
        <el-col :span="12">
          <common-table :tableHead="tableHead" :data="tableData" :highlight="true" :pagination="pagination" @operate="operate" @turnPage="search">
            <template slot="globalOperate">
              <el-button class="small_btn" type="text" @click.stop="add"><i class="el-icon-plus"></i><span class="font-color">{{$t('public.add')}}</span ></el-button>
            </template>
          </common-table>
        </el-col>
        <el-col :span="12">
          <el-form label-position="top" :rules="rules" ref="form" :model="form" class="padding-b" v-show="addFormShow">
            <el-form-item :label="$t('monitor.monitorName')" prop="name">
              <el-input size="mini" v-model.trim="form.name" :maxlength="20"></el-input>
            </el-form-item>
            <el-form-item :label="$t('monitor.monitorType')">
              <el-radio-group v-model.trim="form.monitorType" @change="changeType" v-if="addFormShow">
                <el-radio size="mini" :label="'call'">{{$t('monitor.table')}}</el-radio>
                <el-radio size="mini" :label="'multi'">{{$t('monitor.tableIm')}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="$t('monitor.public')">
              <el-radio-group v-model.trim="form.type">
                <el-radio size="mini" :label="$store.state.session.sessionId">{{$t('monitor.jICanSee')}}</el-radio>
                <el-radio size="mini" :label="'all'">{{form.monitorType === "call"? $t('monitor.allCanSee'): $t('monitor.allCanSee1')}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <div v-show="form.monitorType === 'call'">
              <el-form-item>
                <el-checkbox v-model.trim="form.phoneServiceNos">{{$t('monitor.callNumMonitor')}}</el-checkbox>
              </el-form-item>
              <el-form-item>
                <el-select size="mini"
                           :multiple="true"
                           :filterable="true"
                           :disabled="!form.phoneServiceNos"
                           v-model.trim="form.phoneServiceNosArr"
                           :placeholder="$t('public.pleasePick')"
                           class="width-full">
                  <el-option
                    v-for="(item, index) in dataArray.phoneServiceNos"
                    v-if="item.PBX === pbx"
                    :label="item.DisplayName ? item.Exten + '('+item.DisplayName + ')' : item.Exten"
                    :key="index"
                    :value="item.Exten">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model.trim="form.phoneQueues">{{$t('monitor.callSkillMonitor')}}</el-checkbox>
              </el-form-item>
              <el-form-item>
                <el-select size="mini"
                           :multiple="true"
                           :filterable="true"
                           v-model.trim="form.phoneQueuesArr"
                           :disabled="!form.phoneQueues"
                           :placeholder="$t('public.pleasePick')"
                           class="width-full">
                  <el-option
                    v-for="(item, index) in dataArray.phoneQueues"
                    :label="item.DisplayName"
                    v-if="item.PBX === pbx"
                    :key="index"
                    :value="item.Exten">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model.trim="form.accountCalls">{{$t('monitor.outCallMonitorList')}}</el-checkbox>
              </el-form-item>
            </div>
            <div v-show="form.monitorType !== 'call'">
              <el-form-item>
                <el-checkbox v-model.trim="form.multiChannel">{{$t('monitor.multiChannelMonitor')}}</el-checkbox>
              </el-form-item>
              <el-form-item>
                <el-select size="mini"
                           :multiple="true"
                           :filterable="true"
                           v-model.trim="form.multiChannelArr"
                           :disabled="!form.multiChannel"
                           :placeholder="$t('public.pleasePick')"
                           class="width-full">
                  <el-option
                    class="max-width"
                    v-for="(item, index) in dataArray.multiChannel"
                    :label="item.companyName"
                    :key="index"
                    :value="item.accessId">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model.trim="form.multiChannelSkill">{{$t('monitor.multiChannelSkillMonitor')}}</el-checkbox>
              </el-form-item>
              <el-form-item>
                <el-select size="mini"
                           :multiple="true"
                           :filterable="true"
                           v-model.trim="form.multiChannelSkillArr"
                           :disabled="!form.multiChannelSkill"
                           :placeholder="$t('public.pleasePick')"
                           class="width-full"
                >
                  <el-option
                    class="max-width"
                    v-for="(item, index) in dataArray.multiChannelSkill"
                    :label="item.DisplayName"
                    :key="index"
                    :value="item.Exten">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
            <el-form-item>
              <el-checkbox v-model.trim="form.AgentPeer">{{$t('monitor.agentMonitor')}}</el-checkbox> <span @click="configHead" class="header">{{$t('monitor.tHeader')}}</span>
            </el-form-item>
            <el-form-item>
              <el-select size="mini"
                         :multiple="true"
                         :filterable="true"
                         v-model.trim="form.currentQueue"
                         @change="handleChange"
                         :disabled="!form.AgentPeer"
                         :placeholder="$t('monitor.allSkills')"
                         class="width-full"
                         v-if="addFormShow"
              >
                <el-option
                  v-for="(item, index) in currentQueueArr"
                  :label="item.DisplayName"
                  :key="index"
                  :value="item._id">
                </el-option>
              </el-select>
              <!-- <el-select size="mini"
                         class="width-full"
                         style="margin-top: 10px"
                         :multiple="true"
                         :filterable="true"
                         v-model.trim="form.selectedAgentList"
                         :disabled="!form.AgentPeer"
                         :placeholder="$t('monitor.allAgents')">
                <el-option
                  v-for="item in dataArray.agents"
                  :label="item.label"
                  :key="item.value"
                  :value="item.value">
                </el-option>
              </el-select> -->
              <m7Select class="el-select" :disabled="!form.AgentPeer" filterable multiple :options="dataArray.agents" v-model="form.selectedAgentList" :placeholder="$t('monitor.allAgents')"></m7Select>
            </el-form-item>
            <el-form-item style="padding-top: 10px">
              <el-button type="primary" @click="submit" class="primary_btn fr">{{$t('public.save')}}</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </affix>
    <header-option :show="isShow" :option="currentHeadOptionsShow"  :noDrag="form.monitorType === 'call'?headOptionsNoShow.call:headOptionsNoShow.multi" type="monitor" v-on:close="close"></header-option>
  </div>
</template>
<script>
  //  import {checkform} from '@/utils/validate.js'
  import affix from './../../ui-modules/affix/Affix.vue'
  import commonTable from '../config/robotConfig/base/CommonTable.vue'
  import headerOption from '../report/base/headerOption.vue'
  import {deepClone} from '@/utils/m7Utils'
  const initForm = {
    name: '',
    monitorType: 'call',
    type: 'own',
    currentQueue: [],
    selectedAgentList: [],
    phoneServiceNos: false,
    multiChannel: false,
    phoneQueues: false,
    multiChannelSkill: false,
    AgentPeer: false,
    accountCalls: false,
    phoneServiceNosArr: [],
    multiChannelArr: [],
    phoneQueuesArr: [],
    multiChannelSkillArr: [],
    AgentPeerArr: [],
    AgentHeadConfig: {}
  }
  export default {
    name: 'tableOption',
    props: {
    },
    data () {
      return {
        initFl: false,
        initF2: true,
        currentQueueLength: 0,
        currentQueueArr: [],
        currentHeadOptionsShow: {},
        addFormShow: false,
        form: deepClone(initForm),
        dataArray: {
          phoneServiceNos: [],
          multiChannel: [],
          phoneQueues: [],
          multiChannelSkill: [],
          queues: [],
          agents: [],
          AgentPeer: []
        },
        tableData: [],
        tableHead: [
          {prop: 'name', label: this.$t('monitor.monitorName')},
          {prop: 'monitorTypeName', label: this.$t('monitor.monitorType')},
          {prop: 'typeName', label: this.$t('monitor.public')},
          {prop: 'createUser', label: this.$t('monitor.createAgent')},
          {prop: 'updateUser', label: this.$t('monitor.updateAgent')},
          {prop: 'updatedTime', label: this.$t('monitor.updateTime')},
          {prop: 'operate', label: this.$t('monitor.operate'), special: 'operate', operate: [{name: this.$t('public.edit'), type: 'edit'}, {name: this.$t('public.delete'), type: 'delete', class: 'delete'}]}
        ],
        isShow: false,
        headOptionsNoShow: {
          multi: [{'name': 'agentName', displayname: this.$t('public.agent'), 'order': 1, 'show': true}, {'name': 'agentNo', displayname: this.$t('public.jobNumber'), 'order': 2, 'show': true}],
          call: [{'name': 'agentName', displayname: this.$t('public.agent'), 'order': 1, 'show': true}, {'name': 'agentNo', displayname: this.$t('public.jobNumber'), 'order': 2, 'show': true}, {'name': 'answerStyle', displayname: this.$t('monitor.answerMode'), 'order': 3, 'show': true}, {'name': 'version', displayname: this.$t('monitor.agentVersion'), 'order': 3, 'show': true}, {'name': 'state', displayname: this.$t('public.state'), 'order': 4, 'show': true}]
        },
        headOptionsShow: {
          call: {},
          multi: {}
        },
        pagination: {
          currentPage: 1,
          count: 0,
          totalPage: 0
        },
        searchObj: {
          page: 1,
          limit: 10
        },
        rules: {
          name: [
            {required: true, message: this.$t('validate.required'), trigger: 'blur'}
          ]
        },
        pbx: this.$store.state.session.user.pbx
      }
    },
    components: {
      affix,
      commonTable,
      headerOption
    },
    watch: {
    },
    methods: {
      changeType (value, flag) {
        if (value === 'call') {
          this.currentQueueArr = this.dataArray.queues
          this.form.multiChannelArr = []
          this.form.multiChannelSkillArr = []
          this.form.multiChannel = false
          this.form.multiChannelSkill = false
          if (!flag) {
            this.form.AgentHeadConfig = this.headOptionsShow.call
          }
        } else {
          this.currentQueueArr = this.dataArray.multiChannelSkill
          this.form.phoneQueuesArr = []
          this.form.phoneServiceNosArr = []
          this.form.phoneQueues = false
          this.form.phoneServiceNos = false
          this.form.accountCalls = false
          if (!flag) {
            this.form.AgentHeadConfig = this.headOptionsShow.multi
          }
        }
        if (!flag) {
          this.form.currentQueue = []
          this.form.selectedAgentList = []
        }
      },
      configHead () {
        // 回显
        if (Object.keys(this.form.AgentHeadConfig).length) {
          let data = deepClone(this.form.AgentHeadConfig)
          if (this.form.monitorType === 'call') {
            data.Config.splice(0, 5)
          } else {
            data.Config.splice(0, 2)
          }
          this.currentHeadOptionsShow = data
        }
        this.isShow = true
      },
      close (type, data) {
        if (type === 'save') {
          data.headers.forEach((item) => {
            item.name = item.name.split('@')[0]
          })
          data.Config = data.headers
          data.ReportName = data.reportName
          delete data.headers
          delete data.reportName
          this.form.AgentHeadConfig = data
          this.$message.success('配置表头成功，保存后生效')
        }
        this.isShow = false
      },
      handleChange (value, flag) {
        let data = this.form.currentQueue
        //        先用promise.all 将所有的peer.AssignMembers 集合进arrayList  ,再遍历arrayList发送异步请求，再次使用promise.all 将所有的resp写入agents 待.all完成后，agents就是完整的，进行去重
        let arrayList = []
        if (!flag) {
          this.form.selectedAgentList = []
        }
        if (this.currentQueueLength > data.length) {
          this.form.selectedAgentList = []
        }
        this.currentQueueLength = data.length
        this.dataArray.agents = []
        if (data.length !== 0) {
          // 先用promise把所有的AssignMembers写入arrayList
//          let queues = this.form.monitorType === 'call' ? 'queues' : 'mailQueues'
//          let promise1 = data.map((item) => {
//            return this.$store.dispatch('getCache', {type: queues, id: item}).then((peer) => {
//              let AssignMembers = peer.AssignMembers || []
//              for (let i = 0; i < AssignMembers.length; i++) {
//                let one = AssignMembers[i]
//                if (arrayList.indexOf(one.agentID) === -1) {
//                  arrayList.push(one.agentID)
//                }
//              }
//            })
//          })
          data.map((item) => {
            this.currentQueueArr.map((obj) => {
              if (obj._id === item) {
                let AssignMembers = obj.AssignMembers || []
                for (let i = 0; i < AssignMembers.length; i++) {
                  let one = AssignMembers[i]
                  if (arrayList.indexOf(one.agentID) === -1) {
                    arrayList.push(one.agentID)
                  }
                }
              }
            })
          })
          arrayList.forEach((item2) => {
            let all = this.$agentsMap() || {}
            let agent = all[item2] || ''
            if (agent) {
              this.dataArray.agents.push({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id })
            }
          })
//          Promise.all(promise1).then(() => {
//            // 等所有的都取出来以后，此时arrayList为完整的集合,进行第二次遍历请求，
//            arrayList.forEach((item2) => {
//              let all = this.$store.getters.agents || {}
//              let agent = all[item2] || ''
//              if (agent) {
//                this.dataArray.agents.push({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id })
//              }
//            })
//          })
        } else {
          this.dataArray.agents = this.agentsAll
        }
      },
      search (page) {
        this.searchObj.page = typeof page === 'number' ? page : 1
        this.$store.dispatch('getMonitorList', this.searchObj).then((res) => {
          if (res.success) {
            this.pagination.count = res.count
            this.pagination.currentPage = this.searchObj.page
            let list = res.list
            let arr = []
            for (let i = 0; i < list.length; i++) {
              let question = list[i]
              let typeName = question.type === 'all' ? this.$t('monitor.allCanSee1') : this.$t('monitor.jICanSee')
              let monitorTypeName = question.monitorType === 'multi' ? this.$t('monitor.tableIm') : this.$t('monitor.table')
              let agent = this.$agentsMap() || {}
              let updateUser = agent[question.updateUser] ? agent[question.updateUser].displayName : ''
              let createUser = agent[question.createUser] ? agent[question.createUser].displayName : ''
              arr.push({createUser, updateUser, updatedTime: question.updatedTime, monitorTypeName, typeName, operate: '1', _id: question._id, name: question.name})
            }
            this.tableData = arr
          }
        })
      },
      operate (event) {
        let type = event.type
        if (type === 'edit') {
          if (this.$refs['form']) {
            this.$refs['form'].resetFields()
          }
          this.addFormShow = false
          this.form = deepClone(initForm)
          this.$store.dispatch('showMonitorConfig', {_id: event.val._id})
            .then(resp => {
              if (resp.success) {
                this.addFormShow = true
                for (let i in this.form) {
                  this.form[i] = resp.data[i]
                  if (i === 'AgentHeadConfig') {
                    let type = resp.data.monitorType
                    this.form.AgentHeadConfig = deepClone(type === 'multi' ? this.headOptionsShow.multi : this.headOptionsShow.call)
                    let data = resp.data[i]
                    this.form.AgentHeadConfig.Config.forEach((item) => {
                      data.Config.some((one) => {
                        if (item.name === one.name) {
                          item.show = one.show
                          return true
                        } else {
                          item.show = false
                        }
                      })
                    })
                  }
                }
                this.form._id = resp.data._id
                this.form.createUser = resp.data.createUser
                // 老数据
                if (!this.form.monitorType) {
                  this.form.monitorType = 'call'
                  this.form.AgentHeadConfig = this.headOptionsShow.call
                }
                this.changeType(this.form.monitorType, true)
                this.handleChange(null, true)
              }
            })
        } else if (type === 'delete') {
          this.ignoreQuestion(event.val._id)
        }
      },
      ignoreQuestion (_id) {
        this.$confirm(this.$t('monitor.deleteTips'), this.$t('public.delete'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          cancelButtonText: this.$t('public.cancel'),
          type: 'warning'
        })
          .then(() => {
            this.$store.dispatch('removeMonitorConfig', {_id: _id})
              .then(resp => {
                if (resp.success) {
                  this.$emit('updateTabs')
                  this.search()
                  this.$message({
                    type: 'success',
                    message: this.$t('monitor.deleteSuccess')
                  })
                }
              })
          })
      },
      add () {
        this.addFormShow = true
        this.form = deepClone(initForm)
        if (this.$refs['form']) {
          this.$refs['form'].resetFields()
        }
        this.form.AgentHeadConfig = deepClone(this.headOptionsShow.call)
      },
      submit () {
        // form有_id为编辑,没有为添加
        this.$refs.form.validate((valid) => {
          if (valid) {
            console.log(this.form)
            if ((!this.form.accountCalls) && (!this.form.AgentPeer) && (!this.form.phoneServiceNos) && (!this.form.multiChannel) && (!this.form.phoneQueues) && (!this.form.multiChannelSkill)) {
              this.$message.error(this.$t('monitor.formTip1'))
              return
            }
            if (this.form.phoneServiceNos && this.form.phoneServiceNosArr.length === 0) {
              this.$message.error(this.$t('monitor.formTip2'))
              return
            }
            if (this.form.multiChannel && this.form.multiChannelArr.length === 0) {
              this.$message.error(this.$t('monitor.formTip3'))
              return
            }
            if (this.form.phoneQueues && this.form.phoneQueuesArr.length === 0) {
              this.$message.error(this.$t('monitor.formTip4'))
              return
            }
            if (this.form.multiChannelSkill && this.form.multiChannelSkillArr.length === 0) {
              this.$message.error(this.$t('monitor.formTip5'))
              return
            }
            if (this.form._id && this.form.type !== 'all' && this.form.createUser !== this.form.type) {
              this.$message.error(this.$t('monitor.formTip6'))
              return
            }
            if (this.form.currentQueue.length && !this.form.selectedAgentList.length) {
              this.form.AgentPeerArr = this.dataArray.agents.map((item) => {
                return item.value
              })
            } else {
              this.form.AgentPeerArr = this.form.selectedAgentList
            }
            let data = this.form
            if (data.monitorType === 'call') {
              data.multiChannel = false
              data.multiChannelSkill = false
              data.multiChannelArr = []
              data.multiChannelSkillArr = []
            } else {
              data.phoneServiceNos = false
              data.phoneQueues = false
              data.accountCalls = false
              data.phoneQueuesArr = []
              data.phoneServiceNosArr = []
            }
            this.$store.dispatch('updateMonitorConfig', this.form)
              .then(resp => {
                if (resp.success) {
                  this.addFormShow = false
                  this.$emit('updateTabs')
                  this.search()
                  this.$message({
                    type: 'success',
                    message: this.$t('monitor.saveSuccess')
                  })
                }
              })
          }
        })
      }
    },
    mounted () {
    },
    beforeMount () {
      initForm.type = this.$store.state.session.sessionId
      let p1 = this.$store.dispatch('getCache', {type: 'serviceNo'})
      let p2 = this.$store.dispatch('getCache', {type: 'webchatAndSdkConfig'})
      let p3 = this.$store.dispatch('getCache', {type: 'mailQueues'})
      let p4 = this.$store.dispatch('getCache', {type: 'queues'})
      let p5 = this.$store.dispatch('getCache', {type: 'agents'})
      Promise.all([p1, p2, p3, p4, p5]).then(([res1, res2, res3, res4, res5]) => {
        this.dataArray.phoneServiceNos = res1
        this.dataArray.multiChannel = res2
        this.dataArray.multiChannelSkill = res3
        this.dataArray.phoneQueues = res4
        this.dataArray.queues = res4
        this.currentQueueArr = res4
        this.dataArray.AgentPeer = res5
        let agent = []
        if (this.$store.getters.userHidden === 'yes') {
          if (this.$store.getters.filterStopAgents) {
            agent = this.$store.getters.filterStopAgents.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id }))
          }
        } else {
          agent = res5.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id }))
        }
        this.dataArray.agents = agent
        this.agentsAll = agent
        this.search()
      })
      // 初始化表头
      this.$store.dispatch('getReportTableHeader', 'im_monitor_agent_call').then((res) => {
        res.Config.forEach((item) => {
          item.show = true
        })
        this.headOptionsShow.call = res
      })
      this.$store.dispatch('getReportTableHeader', 'im_monitor_agent_multi').then((res) => {
        res.Config.forEach((item) => {
          item.show = true
        })
        this.headOptionsShow.multi = res
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import '../../../assets/common.styl';
  .wrap
    padding 15px
    overflow auto
  .width-full
    width: 100%
  .padding-b
    padding-bottom 10px
  .promt
    font-size 12px
    color $c-prompt
  .header
    margin-left: 10px;
    cursor pointer
    color $c-main
  .max-width
    max-width 800px  
</style>
